package com.yy.QSManage.tool;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

public class ExcelTool {

    /**
     * 导出文件
     * @param response 接口响应
     * @param fieldAlias 别名
     * @param datas 导出数据
     * @param excelName excel名称
     * @throws IOException
     */
    public static void exportExcel(HttpServletResponse response, LinkedHashMap<String, String> fieldAlias, List<Object> datas, String excelName) throws IOException {
        // 导出为xlsx
        ExcelWriter writer = ExcelUtil.getWriter(true);
        // 设置写入内容统一样式
        CellStyle cellStyle = writer.getCellStyle();
        // 取消默认边框
        cellStyle.setBorderBottom(BorderStyle.NONE);
        cellStyle.setBorderTop(BorderStyle.NONE);
        cellStyle.setBorderLeft(BorderStyle.NONE);
        cellStyle.setBorderRight(BorderStyle.NONE);
        writer.setHeaderAlias(fieldAlias);
        writer.setOnlyAlias(true);
        if(Objects.isNull(datas) || datas.isEmpty()){
            writer.writeHeadRow(fieldAlias.keySet());
        }else{
            writer.write(datas, true);
        }
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        response.setHeader("Content-Disposition", StrUtil.format("attachment;filename={}.xlsx", excelName));
        ServletOutputStream out=response.getOutputStream();
        writer.flush(out, true);
        writer.close();
        IoUtil.close(out);
    }
}
